//
// File: client.cpp
// Description: 
//

#include "client.h"

//
//
Client::Client(Socket &s) : 
	s(s), state(AUTH), alive(true) 
{
	cout << "Connection from: " << s.toString() << endl;
}

//
//
void Client::run() {
	int r = 1; 
	
	while (r > 0) {
		switch (state) {
			case AUTH:
				r = loginState();
				break;
			case GAME:
				r = gameState();
		}
	}
	
	
	if (r < 0) cerr << "Error reading socket from " << s.toString() << endl;
	cout << "Client disconnecting [" << s.toString() << "]" << endl;
}

//
//
int Client::loginState() {
	dHeader header;
	int len = s.recv(&header, sizeof(header));
	if (len < 1) return len;
	
	switch (header.type) {
		case LOGIN_REQUEST: {
			cout << "Asked to login by " << s.toString() << endl;
			dLoginRequest login;
			len = s.recv(&login, sizeof(login));
			
			cout << "Tried to login with : (" 
				<< login.username << ", " << login.password << ")" << endl;
			
			dLoginResponse res;
			if (!Database::get().usernameExists(login.username)) {
				// user doesn't exist
				res.type = USER_DOESNT_EXIST;
			} else if (!Database::get().login(login.username , login.password )) {
				// Wrong password
				res.type = BAD_PASSWORD;
			} else {
				// A-OK
				res.type = SUCCESS;
			}
			s.send(&res, sizeof(res));
			
			break;
		}
		case CREATE_ACCOUNT: {
			cout << "Asked to create account by " << s.toString() << endl;
			dCreateAccount login;
			len = s.recv(&login, sizeof(login));
			
			cout << "Tried to create account with: (" 
				<< login.username << ", " << login.password << ")" << endl;
			
			dCreateResponse res;
			if (Database::get().createUser(login.username, login.password)) {
				// success
				res.type = SUCCESS;
			} else {
				// username exists
				res.type = USER_NAME_TAKEN;
			}
			s.send(&res, sizeof(res));
			
			
			break;
		}
	}

	
	return len;
}

//
//
int Client::gameState() {
	
	
	return 0;
}
